package com.example.receiptocr.data

import android.content.Context
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.runBlocking
import dagger.hilt.android.qualifiers.ApplicationContext

@Singleton
class TokenDataStore @Inject constructor(
    @ApplicationContext private val context: Context // 添加 @ApplicationContext 注解
) {

    companion object {
        private val Context.dataStore by preferencesDataStore(name = "auth_tokens")
        val TOKEN_KEY = stringPreferencesKey("auth_token")
    }

    // 保存 Token
    suspend fun saveToken(token: String) {
        context.dataStore.edit { preferences ->
            preferences[TOKEN_KEY] = token
        }
    }

    // 读取 Token
    fun getToken(): Flow<String?> {
        return context.dataStore.data.map { preferences ->
            preferences[TOKEN_KEY]
        }
    }

    // 同步获取 Token（缓存）
    fun getTokenSync(): String? {
        return try {
            runBlocking {
                getToken().firstOrNull()
            }
        } catch (e: Exception) {
            null
        }
    }

    // 清除 Token（用于登出）
    suspend fun clearToken() {
        context.dataStore.edit { preferences ->
            preferences.remove(TOKEN_KEY)
        }
    }
}
